package com.uni.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.uni.util.ReturnData;

@Controller
@RequestMapping("login")
public class LoginController {


    @RequestMapping("logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/login.jsp";
    }

    @RequestMapping("login")
    @ResponseBody 
    public ReturnData login(HttpServletRequest request){
    	String name = request.getParameter("name");
    	String password = request.getParameter("password");
    	ReturnData rd = new ReturnData();
        if(StringUtils.isEmpty(name)){
        	return rd.failBack("用户名不能为空");
        }
        if(StringUtils.isEmpty(password)){
        	return rd.failBack("密码不能为空");
        }
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
		token.setRememberMe(true);
		Subject subject = SecurityUtils.getSubject();
		if(subject!=null){
			try{
				subject.login(token);
			}catch (Exception e) {
				return rd.failBack("用户名或者密码错误");
			}
		}
		return rd.okBack("登录成功");
    }
}